#include "swoole.h"

static int swMutex_lock(swLock *lock);
static int swMutex_unlock(swLock *lock);
static int swMutex_trylock(swLock *lock);
static int swMutex_free(swLock *lock);

int swMutex_create(swLock *lock,int use_in_process){
	bzero(lock,sizeof(swLock));
	lock->type = SW_MUTEX;

	pthread_mutexattr_init(&lock->object.mutex.attr);
	if(use_in_process){
		pthread_mutexattr_setpshared(&lock->object.mutex.attr,PTHREAD_PROCESS_SHARED);
	}
	pthread_mutex_init(&lock->object.mutex._lock,&lock->object.mutex.attr);

	lock->lock = swMutex_lock;
	lock->unlock = swMutex_unlock;
	lock->trylock = swMutex_trylock;
	lock->free = swMutex_free;

	return 0;
}

static int swMutex_lock(swLock *lock){
	return pthread_mutex_lock(&lock->object.mutex._lock);
}

static int swMutex_unlock(swLock *lock){
	return pthread_mutex_unlock(&lock->object.mutex._lock);
}

static int swMutex_trylock(swLock *lock){
	return pthread_mutex_trylock(&lock->object.mutex._lock);
}

static int swMutex_free(swLock *lock){
	pthread_mutexattr_destroy(&lock->object.mutex.attr);
	return pthread_mutex_destroy(&lock->object.mutex._lock);
}
